package com.shh.aiojbackendserver.config;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * 服务降级配置 多个模块配置
 */
@Configuration
public class RateLimitsConfig {

    /**
     * 配置速率限制器 防止用户频繁提交表单
     * @return
     */
    // 通用注册表
    @Bean
    public RateLimiterRegistry rateLimiterRegistry() {
        return RateLimiterRegistry.ofDefaults();
    }

    // 用户模块限流器 - 3秒1次
    @Bean("userRateLimiter")
    public RateLimiter userRateLimiter(RateLimiterRegistry registry) {
        return registry.rateLimiter("userModule",
                RateLimiterConfig.custom()
                        .limitRefreshPeriod(Duration.ofSeconds(3))
                        .limitForPeriod(1)
                        .timeoutDuration(Duration.ZERO)
                        .build());
    }

    // 订单模块限流器 - 5秒1次
    @Bean("orderRateLimiter")
    public RateLimiter orderRateLimiter(RateLimiterRegistry registry) {
        return registry.rateLimiter("orderModule",
                RateLimiterConfig.custom()
                        .limitRefreshPeriod(Duration.ofSeconds(5))
                        .limitForPeriod(1)
                        .timeoutDuration(Duration.ofMillis(500)) // 可等待500ms
                        .build());
    }
}
